const {
    Msg,
    Code,
    Constant
} = require('./consts');
const {
    apiGetSonList,
    apiGetGrandSonList,
    apiGetUserMoneyAndOil,
    apiTotalOil,
    getUserInfo,
    getQrCode,
    apiGetParentInfo,
    apiReduceMoney,
    apiWithdrawMoney,
    apiGetTotalWithdraw,
} = require('./api');
const {
    cacheSonList, //获取缓存中的徒弟信息
    updateSonCache,
    cacheGrandSonList,
    updateGrandSonCache
} = require('./cache');
const {
    checkWithdraw
} = require('./dao');

const withdraw = require('../../../domain/withdraw');
const time = require('../../../util/time');
const httpRequest = require('request');
const uuid = require('node-uuid');


/**
 * 获取徒弟信息
 * @param session
 * @param uid
 * @param pageNum
 * @returns {Promise<any|unknown>}
 */
exports.getSonList = async function ({session, uid, pageNum}) {
    //缓存数据
    let cacheData = await cacheSonList.call(this, uid, pageNum);
    //有缓存返回
    if (cacheData.length > 0) {
        return cacheData;
    }
    //没有缓存去mongo中查询
    let users = await apiGetSonList.call(this, session, uid, pageNum);
    if (users.length > 0) {
        //更新缓存中的徒弟信息
        await updateSonCache.call(this, uid, pageNum, users);
    }
    return users;
}

/**
 * 获取徒孙信息
 * @param session
 * @param uid
 * @param pageNum
 * @returns {Promise<any|unknown>}
 */
exports.getGrandSonList = async function ({session, uid, pageNum}) {
    //缓存数据
    let cacheData = await cacheGrandSonList.call(this, uid, pageNum);
    //有缓存返回
    if (cacheData.length > 0) {
        return cacheData;
    }
    //没有缓存去mongo中查询
    let users = await apiGetGrandSonList.call(this, session, uid, pageNum);
    if (users.length > 0) {
        //更新缓存中的徒弟信息
        await updateGrandSonCache.call(this, uid, pageNum, users);
    }
    return users;
}

/**
 * 获取收益主页相关信息
 * @param session
 * @param uid
 * @returns {Promise<{oil: *, apprentice_oil: {default: number, type: Number | NumberConstructor}, disciple_oil_today: {default: number, type: Number | NumberConstructor}, percentage: string, apprentice_oil_today: {default: number, type: Number | NumberConstructor}, today_money: number, total_money: *, disciple_oil: {default: number, type: Number | NumberConstructor}}>}
 */
exports.getPlayerHome = async function ({session, uid}) {
    let userInfo = await getUserInfo.call(this, session, uid);
    if (!userInfo) {
        throw new Error(Msg.USER_NOT_FOUND);
    }
    //获取余额和石油
    let {total_money, oil} = await apiGetUserMoneyAndOil.call(this, session, uid);
    let {sum_oil} = await apiTotalOil.call(this, session);
    let percent = 0;
    if (sum_oil > 0) {
        percent = oil / sum_oil * 100;
    }

    return {
        oil: oil,
        percentage: percent.toFixed(4) + '%',
        total_money: total_money,
        apprentice_oil: userInfo.apprentice_oil,
        disciple_oil: userInfo.disciple_oil,
        apprentice_oil_today: userInfo.apprentice_oil_today,
        disciple_oil_today: userInfo.disciple_oil_today,
    };
}

/**
 * 获取用户的海报信息
 * @param session
 * @param uid
 * @returns {Promise<{default: string, type: StringConstructor}|{default: string, type: String | StringConstructor}|User.strip.share_poster>}
 */
exports.getSharePoster = async function ({session, uid}) {
    //判断用户是否存在
    let userInfo = await this.app.userRemote(uid, 'get', [uid, 'user']);
    if (!userInfo) {
        throw new Error(Msg.USER_NOT_FOUND);
    }
    if (userInfo.share_poster) {
        return userInfo.share_poster;
    }
    //二维码
    let qrCode = await getQrCode.call(this, uid);

    return qrCode;
}

/**
 * 获取父用户信息
 * @param session
 * @param uid
 * @returns {Promise<unknown>}
 */
exports.getMasterInfo = async function ({session, uid}) {
    //判断用户是否存在
    let userInfo = await this.app.userRemote(uid, 'get', [uid, 'user']);
    if (!userInfo) {
        throw new Error(Msg.USER_NOT_FOUND);
    }
    if (userInfo.parent_id == "0") {
        throw new Error(Msg.MASTER_NOT_FOUND);
    }
    let parent = await apiGetParentInfo.call(this, session, userInfo.parent_id);
    return {
        invite_id: parent.invite_id,
        avatar: parent.avatar,
        phone: parent.phone,
        nickname: parent.nickname
    };
}

/**
 * 用户提现
 * @param session
 * @param uid 用户ID
 * @param cate 提现金额类型
 * @returns {Promise<void>}
 */
exports.playerWithdraw = async function ({session, uid, cate}) {
    let self = this;
    let userInfo = await self.app.userRemote(uid, 'get', [uid, 'user']);
    if (!userInfo) {
        throw new Error(Msg.USER_NOT_FOUND);
    }
    let wx_money = 0.3;
    switch (cate) {
        case 0:
            wx_money = 0.3;
            break;
        case 1:
            wx_money = 50;
            break;
        case 2:
            wx_money = 100;
            break;
        case 3:
            wx_money = 200;
            break;
        case 4:
            wx_money = 300;
            break;
        case 5:
            wx_money = 500;
            break;
        case 6:
            wx_money = 1000;
            break;
        default:
            throw new Error(Msg.WITHDRAW_MONEY_ERROR);
            break;
    }
    if (cate == 0) {
        //领取过激励奖金
        if (userInfo.first_withdraw) {
            throw new Error(Msg.ALREADY_TAKE_AWARD);
        } else {
            await self.app.userRemote(uid, "set", [uid, "user.first_withdraw", true]);
        }
        //检查是否有过激励金领取记录
        let check = await checkWithdraw.call(self, uid, wx_money);
        if (check) {
            throw new Error(Msg.ALREADY_TAKE_AWARD);
        }
        //数据库的金额
        let {money} = await apiGetUserMoneyAndOil.call(self, session, uid);
        //余额不足
        if (money < wx_money) throw new Error(Msg.MONEY_INSUFFICIENT);
        userInfo.money = parseFloat(userInfo.money) - wx_money;
        if (userInfo.money < 0) userInfo.money = 0;
        //更新内存
        await this.app.userRemote(uid, "set", [uid, "user.money", userInfo.money]);
        //减少金钱
        await apiReduceMoney.call(self, session, uid, money, userInfo.money);

        if (userInfo.real_open_id) {
            await apiWithdrawMoney.call(self, userInfo.real_open_id, wx_money);
        } else {
            //微信商户提现
            await apiWithdrawMoney.call(self, uid, wx_money);
        }

        //插入提现记录
        let Withdraw = new withdraw({
            wid: uuid.v4(),
            uid: uid,
            real_open_id: userInfo.real_open_id,
            money: wx_money,
            status: 2,
            super_status: 2,
            gmt_create: new Date().valueOf(),
            gmt_modified: new Date().valueOf()
        });
        Withdraw.save(Withdraw, function (err, data) {
            if (!!err) {
                console.error('提现记录 保存失败: ' + err);
            }
        });

    } else {
        //数据库的金额
        let {money, total_money} = await apiGetUserMoneyAndOil.call(self, session, uid);
        //余额不足
        if (money < wx_money) throw new Error(Msg.MONEY_INSUFFICIENT);
        userInfo.money = parseFloat(userInfo.money) - wx_money;
        if (userInfo.money < 0) userInfo.money = 0;
        //更新内存
        await this.app.userRemote(uid, "set", [uid, "user.money", userInfo.money]);
        //减少金钱
        await apiReduceMoney.call(self, session, uid, money, userInfo.money);
        //累积提现总额
        let total_withdraw = await apiGetTotalWithdraw.call(self, session, uid);
        //插入提现记录
        let Withdraw = new withdraw({
            wid: uuid.v4(),
            uid: uid,
            real_open_id: userInfo.real_open_id,
            profits: total_money,
            total_withdraw: total_withdraw,
            money: wx_money,
            status: 2,
            audit_time: new Date().valueOf(),
            super_status: 1,
            gmt_create: new Date().valueOf(),
            gmt_modified: new Date().valueOf()
        });
        Withdraw.save(Withdraw, function (err, data) {
            if (!!err) {
                console.error('提现记录 保存失败: ' + err);
            }
        });
    }

    return;
}

/**
 * 分页查询提现记录
 * @param session
 * @param uid
 * @param pageSize
 * @param pageNum
 * @returns {Promise<void>}
 */
exports.withdrawLog = async function ({session, uid, pageSize, pageNum}) {
    return new Promise((resolve, reject) => {
        let currentPage = (pageNum - 1) * pageSize;
        console.log('currentPage')
        console.log(currentPage)
        console.log('pageSize')
        console.log(pageSize)
        //分页查询提现记录
        withdraw.find({
            uid: uid
        }, function (err, data) {
            if (!!err) {
                return reject(err);
            }
            console.log('data.length')
            console.log(data.length)
            let ret = [];
            //格林尼治to北京
            for (let i = 0; i < data.length; i++) {
                ret.push({
                    wid: data[i].wid,
                    money: data[i].money,
                    status: data[i].super_status,
                    gmt_create: time.gmtToCst(data[i].gmt_create),
                });
            }
            resolve(ret);
        }).skip(currentPage).limit(pageSize).sort({gmt_create: -1});
    });
}

/**
 * 提现信息
 * @param session
 * @param uid
 * @returns {Promise<void>}
 */
exports.withdrawInfoAction = async function ({session, uid}) {
    return {
        0: await checkWithdraw.call(this, uid, 0.3),
        1: await checkWithdraw.call(this, uid, 50),
        2: await checkWithdraw.call(this, uid, 100),
        3: await checkWithdraw.call(this, uid, 200),
        4: await checkWithdraw.call(this, uid, 300),
        5: await checkWithdraw.call(this, uid, 500),
        6: await checkWithdraw.call(this, uid, 1000)
    }
}

